angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
  // Form data for the login modal
  $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    console.log('Doing login', $scope.loginData);

    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

.controller('PlaylistsCtrl', function($scope,GameData,$ionicPopup) {
  $scope.Data= GameData.og;
  // Random();
  var showAlert = function() {
     var alertPopup = $ionicPopup.alert({
       title: '注意',
       template: '游戏已结束！'
     });
     alertPopup.then(function(res) {
        // GameData.reset();
     });
  };

  var Random = function(){
      // i = Math.floor((Math.random()*4));
      // j = Math.floor((Math.random()*4));
    var key = false;
    for(var i=0;i<4;i++){
      for(var j=0;j<4;j++){
        if(GameData.og[i][j].d==0){
          GameData.og[i][j]={d: 2,v: true}
          
          // console.log(GameData.og[i][j]);
          key = true;
          // $scope.Data= GameData.og;
          // return true;
          break;
        }
      }
      if(key){
        break;
      }
    }
  }
  var _totalScore = function(){
    var s=0;
    for(var i=0;i<4;i++){
      for(var j=0;j<4;j++){
        s+=$scope.Data[i][j].d;
      }
    }
    return s;
  }
  $scope.totalScore=_totalScore();
  $scope.onSwipeDown=function(){
    //console.log('down');
    
    GameData.down();
    Random();
    $scope.totalScore=_totalScore();
    //showAlert();
    // console.log();
  // $scope.Data= GameData.og;
  }
  $scope.onSwipeUp=function(){
    //console.log('up');
    GameData.up();
    Random();
  $scope.totalScore=_totalScore();

  }
  $scope.onSwipeLeft=function(){
    //console.log('left');
    GameData.Left();
    Random();
  $scope.totalScore=_totalScore();
  }
  $scope.onSwipeRight=function(){
   // console.log('right');
     GameData.Right();
    Random();
  $scope.totalScore=_totalScore();

  }
  $scope.onDragRight = function(){
     // e.preventDefault();
     // e.stopPropagation();
    return false;
  }
  $scope.isHide = function(x,y){
    if (GameData.og[x][y]==0){
      return true;
    }else{

      return false;
    }
  }
})

.controller('PlaylistCtrl', function($scope, $stateParams) {
})
.controller('browseCtrl', function($scope) {
  $scope.slideHasChanged =function(index){
    console.log(index);
    $scope.slideIndex = index;

  }
});

